import { injectable, Service } from './service'

declare type NetResult = {
  success: boolean,
  data: Any,
  message: string
}

@injectable
export default class NetService extends Service {
  private baseURL: string = import.meta.env.VITE_APIURL
  /**
   * post方法请求接口
   * @param url 接口地址
   * @param params 接口参数
   * @param type POST传参方式
   */
  post (url: string, params: Any = {}, type:string = ''): Promise<NetResult> {
    return new Promise((resolve) => {
      let bodyParams = JSON.stringify(params)
      let urlParams = this.baseURL + url
      if (type === 'posturl') {
        bodyParams = ''
        let paramsString = Object.entries(params)
          .map((item: Any) => `${item[0]}=${item[1]}`)
          .join('&')
        urlParams = this.baseURL + url + '?' + paramsString
      }
      fetch(urlParams, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: bodyParams
      })
        .then(res => {
          if (res.status !== 200) {
            throw res.status
          }
          return res.json()
        })
        .then(res => {
          resolve({
            success: res?.success,
            data: res?.data || null,
            message: res?.message || null
          })
        })
        .catch((err: Any) => {
          resolve({
            success: false,
            data: null,
            message: `请求错误${err.message}`
          })
        })
    })
  }

  /**
   * get请求api接口
   * @param url 接口地址
   */
  get (url: string, params: Any = {}): Promise<NetResult> {
    return new Promise((resolve) => {
      let urlParams = this.baseURL + url
      let paramsString = Object.entries(params)
        .map((item: Any) => `${item[0]}=${item[1]}`)
        .join('&')
      if (Object.keys(params).length) {
        urlParams = this.baseURL + url + '?' + paramsString
      }
      fetch(urlParams, {
        method: 'get',
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => {
          if (res.status !== 200) {
            throw res.status
          }
          return res.json()
        })
        .then(res => {
          resolve({
            success: res?.success,
            data: res?.data || null,
            message: res?.message || null
          })
        })
        .catch((err: Any) => {
          if (err === 401 || err === 402) {
            throw err
          }
          resolve({
            success: false,
            data: null,
            message: `请求错误${err.message}`
          })
        })
    })
  }
}
